package com.onlinelibrary.activities.sign;

import android.annotation.SuppressLint;
import android.app.Application;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.onlinelibrary.databinding.ActivitySignBinding;
import com.onlinelibrary.utils.Http;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SignVM extends AndroidViewModel {
    public static MutableLiveData<String>email=new MutableLiveData<>(),password=new MutableLiveData<>(),password2=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    private static SignActivity signActivity;
    public SignVM(@NonNull Application application) {
        super(application);
        email.setValue("");
        password.setValue("");
        password2.setValue("");
    }
    public void setBinding(ActivitySignBinding binding, SignActivity signActivity){
        SignVM.signActivity=signActivity;
    }
    public static void sign(View view){
        if (!email.getValue().equals("")&&!password.getValue().equals("")&&!password2.getValue().equals("")){
            if (password.getValue().equals(password2.getValue())){
                try {
                    JSONObject jo=new JSONObject();
                    jo.put("email",email.getValue());
                    jo.put("password",password.getValue());
                    jo.put("is_staff",false);
                    Http.post(jo,"user/sign/", new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            e.printStackTrace();
                        }
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                            signActivity.runOnUiThread(() -> {
                                try {
                                    assert response.body() != null;
                                    Toast.makeText(signActivity,response.body().string(), Toast.LENGTH_SHORT).show();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                signActivity.finish();
                            });
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else {
                Toast.makeText(signActivity, "两次密码不一样", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(signActivity, "请填写完整", Toast.LENGTH_SHORT).show();
        }
    }
}
